﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;

namespace testClientSocket
{
    public class SynchronousSocketClient
    {
        public static void startClient(){
            //
            byte[] bytes = new byte[1024];
            try
            {                
                //IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
                //IPHostEntry ipHostInfo = Dns.GetHostByAddress("192.168.0.103");
                //IPAddress ipAddress = ipHostInfo.AddressList[0];
                //IPAddress ipAddress = IPAddress.Parse("192.168.1.8");
                IPAddress ipAddress = IPAddress.Parse("10.10.0.77");
                IPEndPoint remoteEP = new IPEndPoint(ipAddress, 7787);
                
                Socket sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                //Socket sender = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

                try
                {
                    sender.Connect(remoteEP);
                    Console.WriteLine("Socket connected to {0} ", sender.RemoteEndPoint.ToString());
                    byte[] msg = Encoding.ASCII.GetBytes("$2872$KhangVM$123456");
                    int byteSent = sender.Send(msg);
                    //int byteRec = sender.Receive(bytes);
                    //Console.WriteLine("Echoed test = {0}", Encoding.ASCII.GetString(bytes, 0, byteRec));

                    sender.Shutdown(SocketShutdown.Both);
                    sender.Close();
                    //Console.Read();
                }
                catch (ArgumentNullException ane)
                {
                    Console.WriteLine("ArgumentNullException: {0}", ane.ToString());
                }
                catch (SocketException se)
                {
                    Console.WriteLine("SocketException: {0}", se.ToString());
                }
                catch (Exception e)
                {
                    Console.WriteLine("Unknown exception: {0}", e.ToString());
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception: {0}", e.ToString());
            }
        }
    }
}
